package com.loveprogrammer.base.factory;

import com.loveprogrammer.base.network.support.BaseHandler;
import com.loveprogrammer.command.IHandler;
import com.loveprogrammer.command.anotation.TopicListener;
import org.reflections.Reflections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @ClassName HandlerFactory
 * @Description 监听器工厂
 * @Author admin
 * @Date 2024/2/5 11:21
 * @Version 1.0
 */
@Component
@Order(1)
public class HandlerFactory implements CommandLineRunner {

    public static final Logger log = LoggerFactory.getLogger(HandlerFactory.class);

    public Map<Integer, Class> handlerMap = new HashMap<>();

    @Override
    public void run(String... args) throws Exception {
        // 找到所有实现类
        Reflections reflections = new Reflections("com.loveprogrammer.handler");
        // 获取在指定包扫描的目录所有的实现类
        Set<Class<? extends BaseHandler>> classes = reflections.getSubTypesOf(BaseHandler.class);
        for (Class<? extends IHandler> aClass : classes) {
            try {
                TopicListener listeners = aClass.getAnnotation(TopicListener.class);
                Integer topic = listeners.topic();
                handlerMap.put(topic, aClass);
                log.info("初始化消息监听器成功 {}",aClass.getName());
            } catch (Exception e) {
                log.error("初始化" + aClass.getName() + "消息监听器失败",e);
            }
        }
    }
}
